package org.edu.modules.common.lock;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import me.zhyd.oauth.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

@Aspect
@Configuration
public class LockMethodInterceptor
{
    private static final Cache<String, Object> CACHE = CacheBuilder.newBuilder().maximumSize(1000L).expireAfterWrite(20L, TimeUnit.SECONDS).build();

    @Around("execution(public * *(..))  && @annotation(org.edu.modules.common.lock.LocalLock)")
    public Object interceptor(ProceedingJoinPoint joinPoint)
    {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        LocalLock localLock = (LocalLock)method.getAnnotation(LocalLock.class);
        String key = getKey(localLock.key(), joinPoint.getArgs());
        if (!StringUtils.isEmpty(key))
        {
            if (CACHE.getIfPresent(key) != null) {
                throw new RuntimeException("请勿重复请求...! ");
            }
            CACHE.put(key, key);
        }
        try
        {
            Object localObject1 = joinPoint.proceed();return localObject1;
        }
        catch (Throwable throwable)
        {
            throwable = throwable;
            throw new RuntimeException("服务器异常! ");
        }
        finally {}
    }

    private String getKey(String key, Object[] args)
    {
        for (int i = 0; i < args.length; i++) {
            key = key.replace("arg[" + i + "]", args[i].toString());
        }
        return key;
    }
}
